package com.whty.cms.filewps.upload.servlet;

import com.whty.cms.filewps.upload.dto.AttachFile;
import com.whty.cms.filewps.upload.service.IUploadService;
import com.whty.cms.filewps.util.CosUtil;
import com.whty.cms.filewps.util.MapUtil;
import com.whty.cms.filewps.util.MemcacheUtil;
import com.whty.cms.filewps.util.SpringUtils;
import net.sf.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Map;

@WebServlet(urlPatterns = {"/uploadFile"})
@MultipartConfig
public class SimpleUploadServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;
	
	private static final Logger LOGGER = LogManager.getLogger(SimpleUploadServlet.class);
	
//	private IUploadService uploadService = (IUploadService) SpringUtils.getBean("uploadService");
	
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		
		IUploadService uploadService = (IUploadService) SpringUtils.getBean("uploadService");
		BufferedOutputStream out = null;
        ByteArrayInputStream in = null;
        response.setContentType("json/application;charset=UTF-8");
		try {
			Part part = request.getPart("fileData");
			String userId = request.getParameter("userId");
			String fileName = request.getParameter("fileName");
			String applyType = request.getParameter("applyType");
			String sourceType = request.getParameter("sourceType");
			String platformCode = request.getParameter("platformCode");
			JSONObject result = new JSONObject();
			if (part == null) {
				result.put("code", "100001");
				result.put("msg", "未找到上传文件");
				result.put("data", "");
            }else if(StringUtils.isBlank(userId)||StringUtils.isBlank(fileName)||StringUtils.isBlank(applyType)
					||StringUtils.isBlank(sourceType)||StringUtils.isBlank(platformCode)) {
				result.put("code", "100000");
				result.put("msg", "必填参数为空");
				result.put("data", "");
			}else if(!"1".equals(MemcacheUtil.getDatabaseObj(applyType))){
				result.put("code", "100000");
				result.put("msg", "后台上传需要申请");
				result.put("data", "");
			}else {
				Long fileLength = part.getSize();
				String fileMd5 = DigestUtils.md5Hex(part.getInputStream());
				String fileExt = "";
				int idx = fileName.lastIndexOf(".");
				if (idx != -1) {
					fileExt = fileName.substring(idx + 1);
				}
				String cosKey = CosUtil.getCosKey(fileName, userId, platformCode);
				AttachFile attach = new AttachFile();
				attach.setUserId(userId);
				attach.setFileName(fileName);
				attach.setFileExt(fileExt);
				attach.setFileLength(fileLength);
				attach.setFileMd5(fileMd5);
				attach.setApplyType(applyType);
				attach.setSourceType(sourceType);
				attach.setPlatformCode(platformCode);
				attach.setFilePath(cosKey);
				AttachFile att = uploadService.SimpleUploadFile(attach,part.getInputStream());
				
				Map<String, String> map = MapUtil.newHashMap();
				map.put("fid", String.valueOf(att.getFid()));
				map.put("downloadUrl", CosUtil.getAuthDownloadUrl(attach.getFilePath(),attach.getApplyType()));
				result.put("code", "000000");
				result.put("msg", "成功");
				result.put("data", map);
			}
			
			
			out = new BufferedOutputStream(response.getOutputStream());
            in = new ByteArrayInputStream(result.toString().getBytes("UTF-8"));
            byte[] buff = new byte[1024 * 512];
            int len;
            while ((len = in.read(buff)) > 0) {
                out.write(buff, 0, len);
            }
            out.flush();
			
		}catch (Exception ex) {
            if (LOGGER.isErrorEnabled()) {
            	LOGGER.error(ex.getMessage(), ex);
			} else {
				LOGGER.info(ex.getMessage(), ex);
			}
        } finally {
            try {
                if (out != null) out.close();
                if (in != null) in.close();
            } catch (IOException ex) {
                if (LOGGER.isErrorEnabled()) {
                    LOGGER.error(ex.getMessage(), ex);
    			} else {
                    LOGGER.info(ex.getMessage(), ex);
    			}
            }
        }
	}
}
